package huoye.shops;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.codeideology.android.AXIFragmentPagerAdapter;

import java.util.ArrayList;
import java.util.List;

import huoye.shops.base.APIUrls;
import huoye.shops.base.BaseActivity;
import huoye.shops.base.UserManager;
import huoye.shops.huoye.home.fragment.HomeFragment;
import huoye.shops.huoye.message.fragment.MessageFragment;
import huoye.shops.huoye.mine.fragment.MineFragment;
import huoye.shops.huoye.operation.fragment.OperationFragment;
import huoye.shops.widget.RoundImageView;


public class MainActivity extends BaseActivity {

    private TabLayout mTabLayout;
    private Fragment mContent;//记录选中的fragment
    private FragmentManager fm;//fragement管理器
    private AXIFragmentPagerAdapter myFragmentPagerAdapter;
    List<Fragment> fragments = new ArrayList<>();
    List<String> titles = new ArrayList<>();
    List<Integer> imageResId = new ArrayList<>();
    private String[] tags = new String[]{"home", "report", "order", "mine"};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        stateCheck(savedInstanceState);
    }

/*  @Override

    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.e("cdcdcdcd","aaa");
        LoginUtils.closeActivity(this, LoginActivity.class, intent);
    }*/




    @Override
    protected int getContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView(@Nullable Bundle bundle) {
        //初始化控件；  
        initView();
    }

    private void initView() {



       // openPower();

     //   startActivity(EditAddShopActivity.class);

        //使用适配器将ViewPager与Fragment绑定在一起
//        mViewPager = (ViewPager) findViewById(R.id.viewPager);

        //将TabLayout与ViewPager绑定在一起
         mTabLayout = (TabLayout) findViewById(R.id.tabLayout);
//        mTabLayout.setupWithViewPager(mViewPager);

        fragments.add(new HomeFragment());
        fragments.add(new MessageFragment());
        fragments.add(new OperationFragment());
        fragments.add(new MineFragment());

        titles.add(getString(R.string.tab_home));
        titles.add(getString(R.string.tab_message));
        titles.add(getString(R.string.tab_operation));
        titles.add(getString(R.string.tab_mine));


        imageResId.add(R.drawable.tab_home_selector);
        imageResId.add(R.drawable.tab_meassage_selector);
        imageResId.add(R.drawable.tab_operation_selector);
        imageResId.add(R.drawable.tab_mine_selector);

        for (int i = 0; i < fragments.size(); i++) {
            mTabLayout.addTab(mTabLayout.newTab().setCustomView(getTabView(i)));
        }

        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                selectTab(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                TextView tv = (TextView) tab.getCustomView().findViewById(R.id.tv_title);
                ImageView iv = (ImageView) tab.getCustomView().findViewById(R.id.iv_title);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                //复选的
            }
        });
        fm = getSupportFragmentManager();

    }



    //打开定位和存储权限
    private void openPower(){
        if((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED)||ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) !=PackageManager.PERMISSION_GRANTED){
            //如果没有授权，则请求授权
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1311);
            //String数组中为申请的权限，第一个是相机，第二个为修改内存，最后的参数即为申请授权的返回值，我设置的1311
        }
    }


    public View getTabView(int position) {
        View view = LayoutInflater.from(this).inflate(R.layout.tab_bottom, null);
        TextView  tv = (TextView) view.findViewById(R.id.tv_title);

        RoundImageView rvTitle = (RoundImageView) view.findViewById(R.id.rv_title);
        ImageView ivTitle = (ImageView) view.findViewById(R.id.iv_title);




        if (position == 3) {
            ivTitle.setVisibility(View.GONE);
            rvTitle.setVisibility(View.VISIBLE);
            if(UserManager.getInstance().getShopLogo() != null){
                Glide.with(this)
                        .load(APIUrls.COMMON_CONFIG.TYPE_COMMON_ALIYUN+UserManager.getInstance().getShopLogo())
                        .dontAnimate()
                        .placeholder(R.mipmap.ic_wait)
                        .error(R.mipmap.ic_error)
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .into(rvTitle);
            }else {
                rvTitle.setImageResource(R.mipmap.ic_launcher_logo);
            }



        }else {
            ivTitle.setVisibility(View.VISIBLE);
            rvTitle.setVisibility(View.GONE);
        }
        tv.setText(titles.get(position));
        ImageView img = (ImageView) view.findViewById(R.id.iv_title);
        img.setImageResource(imageResId.get(position));
        return view;
    }


    public void selectTab(int position) {
//        mViewPager.setCurrentItem(position);
        switchContent(mContent, fragments.get(position), position);
    }

    public void changeTab(int position) {
        mTabLayout.getTabAt(position).select();
        selectTab(position);
    }




    public void switchContent(Fragment from, Fragment to, int position) {
        if (mContent != to) {
            mContent = to;
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            if (!to.isAdded()) { // 先判断是否被add过
                transaction.hide(from)
                        .add(R.id.content, to, tags[position]).commit(); // 隐藏当前的fragment，add下一个到Activity中
            } else {
                transaction.hide(from).show(to).commit(); // 隐藏当前的fragment，显示下一个
            }
        }
    }

    /**
     * 状态检测 用于内存不足时activity被回收重启的时候保证fragment   不会重叠
     */
    private void stateCheck(Bundle saveInstanceState) {
        if (saveInstanceState == null) {
            FragmentTransaction frs = getSupportFragmentManager().beginTransaction();
            mContent = fragments.get(0);
            frs.add(R.id.content, mContent);
            frs.commit();
        } else {
            //通过tag找回失去引用但是存在内存中的fragment.id相同
            Fragment counselorSaleFrag = getSupportFragmentManager().findFragmentByTag(tags[0]);
            Fragment counselorServerFrag = getSupportFragmentManager().findFragmentByTag(tags[1]);
            getSupportFragmentManager().beginTransaction().show(counselorSaleFrag).hide(counselorServerFrag).commit();
        }
    }

    // 定义一个变量，来标识是否退出
    private static boolean isExit = false;

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    //双击返回退出当前app
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            makeToast("再按一次退出程序");
            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            //退出APP
            finish();
        }
    }


}
